#!/usr/bin/env python3
import sys
import rclpy
from rclpy.node import Node
from rclpy.action import ActionClient
from action_tutorials_interfaces.action import Fibonacci


class FibonacciActionClient(Node):
    def __init__(self):
        super().__init__('fibonacci_action_client')

        # 创建 Action 客户端
        self._action_client = ActionClient(self, Fibonacci, 'fibonacci')

        self.get_logger().info('Fibonacci Action Client 已启动')

    def send_goal(self, order: int):
        """发送目标请求"""
        goal_msg = Fibonacci.Goal()
        goal_msg.order = order

        # 等待 Action 服务器可用
        if not self._action_client.wait_for_server(timeout_sec=10.0):
            self.get_logger().error('Action 服务器不可用')
            return None

        self.get_logger().info(f'发送目标: 计算前 {order} 个斐波那契数')

        # 发送目标，设置反馈回调
        send_goal_future = self._action_client.send_goal_async(
            goal_msg,
            feedback_callback=self.feedback_callback
        )

        return send_goal_future

    def feedback_callback(self, feedback_msg):
        """处理反馈信息"""
        feedback = feedback_msg.feedback
        self.get_logger().info(f'收到反馈: {feedback.partial_sequence}')


def main(args=None):
    rclpy.init(args=args)

    # 检查命令行参数
    if len(sys.argv) != 2:
        print("用法: python3 fibonacci_action_client.py <数字>")
        return

    try:
        order = int(sys.argv[1])
        if order < 0:
            print("请输入非负整数")
            return
    except ValueError:
        print("请输入有效的整数")
        return

    node = FibonacciActionClient()

    # 发送目标
    future = node.send_goal(order)

    if future is None:
        return

    # 等待目标被接受
    rclpy.spin_until_future_complete(node, future)

    goal_handle = future.result()

    if not goal_handle.accepted:
        node.get_logger().info('目标被拒绝')
        return

    node.get_logger().info('目标被接受，等待结果...')

    # 等待最终结果
    result_future = goal_handle.get_result_async()
    rclpy.spin_until_future_complete(node, result_future)

    result = result_future.result().result
    node.get_logger().info(f'最终结果: {result.sequence}')

    node.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()